/*
 * Project Name: xdtech-core
 * File Name: CustomSimpleMappingExceptionResolver.java
 * Copyright: Copyright(C) 1985-2015 ZKTeco Inc. All rights reserved.
 */
package com.xdtech.web.resolver;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * TODO 一句话功能简述，请确保和下面的block tags之间保留一行空行
 * <p>
 * TODO 功能详细描述，若不需要请连同上面的p标签一起删除
 * 
 * @author <a href="max.zheng@zkteco.com">郑志雄</>
 * @version TODO 添加版本
 * @see 相关类或方法，不需要请删除此行
 * @since 2015-5-19 下午1:06:37
 */
public class CustomSimpleMappingExceptionResolver extends
													SimpleMappingExceptionResolver
{
	private Log log = LogFactory.getLog(CustomSimpleMappingExceptionResolver.class);
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
												HttpServletResponse response, Object handler, Exception ex)
	{
		// Expose ModelAndView for chosen error view.  
		String viewName = determineViewName(ex, request);
		log.error("MVC异常反馈,重新定向页面="+viewName,ex);
		if (viewName != null)
		{// JSP格式返回  
			if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
					.getHeader("X-Requested-With") != null && request
					.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)))
			{
				// 如果不是异步请求  
				//Apply HTTP status code for error views, if specified.  
				//Only apply it if we're processing a top-level request.  
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null)
				{
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				return getModelAndView(viewName, ex, request);
			}
			else
			{// JSON格式返回  
				try
				{
					PrintWriter writer = response.getWriter();
					writer.write("{\"attributes\":null,\"msg\":\"系统处理错误,请联系管理员.\",\"obj\":null,\"success\":false}");
					writer.flush();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
				return null;

			}
		}
		else
		{
			return null;
		}
	}
}
